/**
 * $Id: ItemListView.m 24 2008-01-09 07:25:37Z robertsaenz $
 */
#import <Foundation/Foundation.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UIKit.h>

#import "MobileShoppingListApplication.h"
#import "ItemListView.h"
#import "Item.h"

@implementation ItemListView

- (id)initWithFrame:(struct CGRect)frame {
	self = [super initWithFrame:frame];
	editMode = NO;
	viewType = ITEMLIST;
	viewTitle = @"Items";
	UITableColumn *col = [[UITableColumn alloc] initWithTitle:@"Checkboxes" identifier:@"checkboxes" width:frame.size.width];
	[self setRowHeight:45.0f];
	[self addTableColumn:col];

	[self setSeparatorStyle:1];
	[self setDataSource: self];
	[self setDelegate: self];

	checked = [UIImage applicationImageNamed:@"checkbox_on.png"];
	unchecked = [UIImage applicationImageNamed:@"checkbox_off.png"];
	delete = [UIImage applicationImageNamed:@"delete.png"];
	return self;
}

- (void) addItem: (NSString *) itemName {
	UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
	[cell setTitle: itemName];
	[cell setImage: unchecked];
	Item *item = [[Item alloc] initWithSelected: NO andName: [cell title]];
	[cellData addObject: item];
	[cells addObject: cell];
	[cell release];
	[item release];
}

- (void) toggleEditMode {
	editMode = !editMode;
	if (editMode) {
		[self reloadData];
	}
}

- (BOOL) getEditMode {
	return editMode;
}

- (void) changeCellStatus: (UIImageAndTextTableCell *) cell withItem: (Item *) item {
	if(  [item isSelected] == NO ) {
		[item setSelected: YES];
		[cell setImage: checked];
	} else {
		[item setSelected: NO];
		[cell setImage: unchecked];
	}
}

- (void) setCellStatus: (UIImageAndTextTableCell *) cell withItem: (Item *) item {
	if(  [item isSelected] == NO ) {
		[cell setImage: unchecked];
	} else {
		[cell setImage: checked];
	}
}

// Data source methods
- (UITableCell*) table: (UITable*)table cellForRow: (int)row column: (int)col {
	UIImageAndTextTableCell *cell = [cells objectAtIndex: row];
	if(editMode) {
		[cell setImage: delete];
	} else {
		Item *item = [cellData objectAtIndex: row];
		[self setCellStatus: cell withItem: item];
	}
	return cell;
}

// Delegate methods
- (void)tableRowSelected:(NSNotification *)notification {
	if( !editMode ) {
		Item *item = [cellData objectAtIndex: [self selectedRow]];
		UIImageAndTextTableCell *cell = [cells objectAtIndex: [self selectedRow]];
		[self changeCellStatus: cell withItem: item];
	} else {
		[sl showConfirmation: @"Delete shopping list item?" withTitle: @"Delete item" andConfirmType: DELITEM];
	}
}

@end
